﻿using QFramework;
using UnityEngine;
using System.Collections.Generic;
using System.Linq;

public class ResultManager : AbstractSystem
{
    private int _stepCount = -1;
    private float _timeTaken = 0f;

    public int StepCount
    {
        get => _stepCount;
        set
        {
            _stepCount = value;
            HandleNewScore(value);
        }
    }

    public float TimeTaken
    {
        get => _timeTaken;
        set => _timeTaken = value;
    }

    private const string ScoresKey = "TopStepScores";
    private List<int> topScores = new List<int>();

    private static bool sInitialized = false;

    public static void Init()
    {
        if (sInitialized) return;

        MyArchitecture.InitArchitecture();
        MyArchitecture.Interface.RegisterSystem(new ResultManager());

        sInitialized = true;
    }

    protected override void OnInit()
    {
        LoadScores();
        Debug.Log("ResultManager 初始化完成");
    }

    // 这里改成重写 OnDeinit()
    protected override void OnDeinit()
    {
        Debug.Log("ResultManager 已释放");
    }

    private void HandleNewScore(int steps)
    {
        if (steps <= 0) return;
        topScores.Add(steps);
        topScores = topScores.OrderBy(s => s).Take(10).ToList();
        SaveScores();
        Debug.Log(FormatLeaderboard(steps));
    }

    private string FormatLeaderboard(int latestStep)
    {
        var sb = new System.Text.StringBuilder();
        sb.AppendLine("🏆 历史步数前十：");
        for (int i = 0; i < topScores.Count; i++)
            sb.AppendLine($"{i + 1}. {topScores[i]} 步");
        if (topScores.Contains(latestStep))
            sb.AppendLine($"✨ 本次成绩 {latestStep} 步已进入排行榜！");
        return sb.ToString();
    }

    private void LoadScores()
    {
        topScores.Clear();
        if (!PlayerPrefs.HasKey(ScoresKey)) return;
        var data = PlayerPrefs.GetString(ScoresKey);
        foreach (var s in data.Split(','))
            if (int.TryParse(s, out int v))
                topScores.Add(v);
        topScores = topScores.OrderBy(s => s).Take(10).ToList();
    }

    private void SaveScores()
    {
        var data = string.Join(",", topScores);
        PlayerPrefs.SetString(ScoresKey, data);
        PlayerPrefs.Save();
    }

    public List<int> GetTopScores() => new List<int>(topScores);
}

//public class MyArchitecture : Architecture<MyArchitecture>
//{
//    protected override void Init()
//    {
//        Debug.Log("架构初始化完成");
//    }
//}
